package drds.plus.executor.sequence_manager;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import drds.plus.sequence.Sequence;
import drds.plus.sequence.impl.SequenceDaoImpl;
import drds.plus.sequence.impl.SequenceImpl;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 直接读取seqeunce表，生成seqeunce配置
 */
@Slf4j
public class DbSequenceManager {
    private LoadingCache<String, Sequence> sequenceNameToSequenceCache = null;


    private String sequenceTableName;//直接连接配置服务器


    protected Sequence getSequence(String sequenceName) {
        try {
            Sequence sequence = sequenceNameToSequenceCache.get(sequenceName);
            return sequence;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public void doInit() {
        sequenceNameToSequenceCache = CacheBuilder.newBuilder().build(new CacheLoader<String, Sequence>() {

            public Sequence load(String tableName) throws Exception {
                return getSequence0(tableName);
            }
        });
        this.sequenceTableName = "sequence";

    }

    public Sequence getSequence0(String sequenceName) {
        Connection connection = null;
        ResultSet resultSet = null;
        try {

            PreparedStatement preparedStatement = connection.prepareStatement("select columnName from " + this.sequenceTableName + " where columnName=?");
            preparedStatement.setString(1, sequenceName);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {

                return new SequenceImpl(new SequenceDaoImpl(), sequenceName);
            }
            return null;
        } catch (SQLException ex) {

            // not exists sequence where on default db indexMapping
            if (ex.getMessage() != null && ex.getMessage().contains("doesn't exist")) {
                throw new RuntimeException("ERR_MISS_SEQUENCE_TABLE_ON_DEFAULT_DB");
            } else if (ex.getMessage() != null && ex.getMessage().contains("Unknown column")) {
                throw new RuntimeException("ERR_SEQUENCE_TABLE_META");
            }

            throw new RuntimeException(ex);

        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                }
            }
        }
    }

    protected void doDestroy() {
        if (sequenceNameToSequenceCache != null) {
            sequenceNameToSequenceCache.cleanUp();
        }
    }

}
